<?php
namespace app\index\controller;
use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
use app\index\validate\Valid;

class System extends Common
{

	//列表
    public function index()
    {
        $title = $this->request->get('title');
        $sn = $this->request->get('sn');
        $zoning = $this->request->get('zoning');
        $provice = $this->request->get('provice');
        $city = $this->request->get('city');
        $zoning_head = $this->request->get('zoning_head');
        $provice_head = $this->request->get('provice_head');
        $stuff = $this->request->get('stuff');
        $wdXianShiLeiXing = $this->request->get('wdXianShiLeiXing');
        $this->assign(array('title'=>$title));
        $this->assign(array('sn'=>$sn));
        $this->assign(array('zoning'=>$zoning));
        $this->assign(array('provice'=>$provice));
        $this->assign(array('city'=>$city));
        $this->assign(array('zoning_head'=>$zoning_head));
        $this->assign(array('provice_head'=>$provice_head));
        $this->assign(array('stuff'=>$stuff));
        $this->assign(array('wdXianShiLeiXing'=>$wdXianShiLeiXing));
        $where = [];
        $where['t.isdel'] = 0;

        if($wdXianShiLeiXing==0){

        }else{
            $where['t2.isdel'] = 0;
        }

        if($title)
            $where['title'] = array('like','%'.$title.'%');
        if($sn)
            $where['title'] = array('like','%'.$sn.'%');
        if($zoning&&!$zoning_head)
            $where['zoning'] = array('exp','in(select id from cg_market_zoning where title like "%'.$zoning.'%")');
        if($provice&&!$provice_head)
            $where['provice'] = array('exp','in(select id from cg_market_provice where title like "%'.$provice.'%")');
        if($city)
            $where['city'] = array('exp','in(select id from cg_market_city where title like "%'.$city.'%")');
        if($zoning_head&&!$zoning)
            $where['zoning'] = array('exp','in(select t.id from cg_market_zoning t join employee t2 on t2.id=t.head where t2.em_name like "%'.$zoning_head.'%")');
        if($provice_head&&!$provice)
            $where['provice'] = array('exp','in(select t.id from cg_market_provice t join employee t2 on t2.id=t.head where t2.em_name like "%'.$provice_head.'%")');
        if($provice_head&&$provice)
            $where['provice'] = array('exp','in(select t.id from cg_market_provice t join employee t2 on t2.id=t.head where t2.em_name like "%'.$provice_head.'%") and provice in(select id from cg_market_provice where title like "%'.$provice.'%") ');
        if($zoning_head&&$zoning)
            $where['zoning'] = array('exp','in(select t.id from cg_market_zoning t join employee t2 on t2.id=t.head where t2.em_name like "%'.$zoning_head.'%") and zoning in(select id from cg_market_zoning where title like "%'.$zoning.'%") ');
        if($stuff){
            //根据模糊查询规则把admin对应的id全部查询出来
            $ids = Db::query("select id from employee where em_name like '%{$stuff}%'");
            $str = [];
            foreach($ids as $k=>$v){
                if($k==0)
                    $str[] = " like '%\"$v[id]\"%' ";
                else
                    $str[] = " stuff like '%\"$v[id]\"%' ";
            }
            $str = implode('or',$str);

            $where['stuff'] = array('exp',$str);
        }

        if($wdXianShiLeiXing==0){
            $count = Db::table('cg_system t')->where($where)->count();
        }else{
            $count = Db::table('cg_system t')->join('cg_system_jxs t2','t2.system_id=t.id','left')->where($where)->count();
        }

        if($wdXianShiLeiXing==0){
            $data = Db::table('cg_system t')->field('*,t.id id')->order("t.id desc")->where($where)->paginate(10,$count);
        }else{
            $data = Db::table('cg_system t')->field('*,t.id id')->join('cg_system_jxs t2','t2.system_id=t.id','left')->order("t.id desc")->where($where)->paginate(10,$count);
        }

//
//        echo Db::table('cg_system')->getLastSql();
        $page = $data->render();
        $data = $data->items();
          $maxpage=ceil($count/10);
        foreach($data as $k=>$v){
            $v['cusername'] = Db::table('users')->where(array('id'=>$v['cuser']))->value('login_name');
            $v['pusername'] = Db::table('users')->where(array('id'=>$v['puser']))->value('login_name');
            $temp = unserialize($v['stuff']);
            $temp = implode(',',$temp);
            $temp = Db::query("select em_name from employee where id in(".$temp.")");
            $temp2 = [];
            foreach($temp as $v1){
                $temp2[] = $v1['em_name'];
            }
            $v['stuff'] = $temp2;

            if($wdXianShiLeiXing==0){
                //查询所有经销商
                $jxs = db('cg_system_jxs')->where('system_id',$v['id'])->column('jxs_id');
                foreach($jxs as $k1=>$v1){
                    $t = [];
                    $t['jxs_id'] = $v1;
                    $t['jxs_title'] = db('cg_jxs')->where('id',$v1)->value('title');
                    $t['jxs_stuff'] = Db::table('cg_jxs')->where(array('id'=>$v1))->value('stuff');
                    if($t['jxs_stuff']){
                        $temp = unserialize($t['jxs_stuff']);
                        $temp = implode(',',$temp);
                        $temp = Db::query("select em_name from employee where id in(".$temp.")");
                        $temp2 = [];
                        foreach($temp as $v11){
                            $temp2[] = $v11['em_name'];
                        }
                        $t['jxs_stuff']= $temp2;
                    }else{
                        $t['jxs_stuff']= '';
                    }
                    $jxs[$k1] = $t;
                }
                $v['jxss'] = $jxs;
            }else{
                $v['jxs_title'] = Db::table('cg_jxs')->where(array('id'=>$v['jxs_id']))->value('title');
                $v['jxs_stuff'] = Db::table('cg_jxs')->where(array('id'=>$v['jxs_id']))->value('stuff');
                if($v['jxs_stuff']){
                    $temp = unserialize($v['jxs_stuff']);
                    $temp = implode(',',$temp);
                    $temp = Db::query("select em_name from employee where id in(".$temp.")");
                    $temp2 = [];
                    foreach($temp as $v1){
                        $temp2[] = $v1['em_name'];
                    }
                    $v['jxs_stuff']= $temp2;
                }else{
                    $v['jxs_stuff']= '';
                }
            }


            $v['cusType'] = Db::table('cg_customertype')->where(array('id'=>$v['cusType']))->value('title');
            $v['oneCType'] = Db::table('cg_channel_types1')->where(array('id'=>$v['oneCType']))->value('title');
            $v['twoCType'] = Db::table('cg_channel_types2')->where(array('id'=>$v['twoCType']))->value('title');
            $v['zoning_title'] = Db::table('cg_market_zoning')->where(array('id'=>$v['zoning']))->value('title');
            $v['provice_title'] = Db::table('cg_market_provice')->where(array('id'=>$v['provice']))->value('title');
            $v['city_title'] = Db::table('cg_market_city')->where(array('id'=>$v['city']))->value('title');
            $v['zoning_head'] = Db::table('cg_market_zoning t')->join('employee t2','t.head=t2.id')->where(array('t.id'=>$v['zoning']))->value('t2.em_name');
            $v['provice_head'] = Db::table('cg_market_provice t')->join('employee t2','t.head=t2.id')->where(array('t.id'=>$v['provice']))->value('t2.em_name');
            $v['city_head'] = Db::table('cg_market_city t')->join('employee t2','t.head=t2.id')->where(array('t.id'=>$v['city']))->value('t2.em_name');
            $v['ctime'] = date('Y-m-d H:i',$v['ctime']);
            $v['ptime'] = date('Y-m-d H:i',$v['ptime']);
            $data[$k] = $v;
        }


        $this->assign('data',$data);
        $this->assign('page',$page);
        $this->assign('maxpage',$maxpage);
        $this->assign('count',$count);
        return $this->fetch('');
    }
    public function add(){


        $validate = new Valid([
            'title'  => 'require|max:100|unique:cg_system|checkJxsmc',
            'stuff'  => 'require',
            'cusType'  => 'require',
            'oneCType'  => 'require',
            'twoCType'  => 'require',
            'detailAddress'  => 'require',
            
        ]);
        $data = [];
        $data['title'] = $this->request->post('title');
        $data['sn'] = $this->request->post('sn');
        $data['cusType'] = $this->request->post('cusType');
        $data['oneCType'] = $this->request->post('oneCType');
        $data['twoCType'] = $this->request->post('twoCType');
        $data['detailAddress'] = $this->request->post('detailAddress');
        $data['jxs'] = $this->request->post('defult_jxs');
        $data['brief'] = $this->request->post('brief');
        $data['stuff'] = $this->request->post('stuff');
        $data['sn'] = $this->request->post('sn');
        $data['attach'] = $this->request->post('attach');
        $data['zoning'] = $this->request->post('zoning');
        $data['provice'] = $this->request->post('provice');
        $data['city'] = $this->request->post('city');

        if (!$validate->check($data)) {
            echo  json_encode([
                "success"=>false,
                "msg"=>$validate->getError()
            ]);die;
        }

        if($data["sn"]){
            $sysck=db("cg_system")->where("sn='{$data["sn"]}'")->find();
            if($sysck){
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"系统编号不能重复"
                ]);die; 
            }
               
        }
        
        $data['stuff'] = explode(',',$data['stuff']);
        $data['stuff'] = serialize($data['stuff']);
        $data['cuser'] = $_SESSION['think']['employee_id'];
        $data['ctime'] = time();
        $data['puser'] = $_SESSION['think']['employee_id'];
        $data['ptime'] = time();
        if($data['attach']){
            $attachids = $data['attach'];
            $data['attach'] = serialize(explode(',',$data['attach']));
        }

        $jxsll = $this->request->post('systemContact/a');
        $jxs = $this->request->post('jxs/a');

        //系统编号为空则自动生成
        if(empty($data['sn'])){
            $year=date("Y")-2000;
                $day=date("md");
                $ckyear=$year.$day;
                $max = Db::query("select max(sn) m from cg_system where sn like '{$ckyear}%' limit 1");
                if($max[0]["m"])
                    $data["sn"]=$max[0]["m"]+1;
                else
                    $data['sn']=$ckyear."0001";
        }

        $bool = Db::table('cg_system')->insert($data);
        if(false !== $bool){
            $insetid = Db::table('cg_system')->getLastInsID();
            //更新附件表
            if(isset($attachids)){
                Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$insetid,'target_table'=>'cg_system'));
            }

            //增加附属系统联络信息表
            if(isset($jxsll)&&is_array($jxsll)){
                $temp  = [];

                foreach($jxsll['name'] as $k=>$v){
                    if($v=='')
                        continue;
                    $temp[] = [
                        'name'=>$v,
                        'system_id'=>$insetid,
                        'phone'=>$jxsll['phone1'][$k].'-'.$jxsll['phone2'][$k],
                        'mobile'=>$jxsll['mobile'][$k],
                        'fax'=>$jxsll['fax1'][$k].'-'.$jxsll['fax2'][$k],
                        'email'=>$jxsll['email'][$k],
                        'job'=>$jxsll['job'][$k],
                        'addr'=>$jxsll['addr'][$k],
                        'zipcode'=>$jxsll['zipcode'][$k],
                        'cuser'=>$_SESSION['think']['employee_id'],
                        'ctime'=>time(),
                        'puser'=>$_SESSION['think']['employee_id'],
                        'ptime'=>time(),
                    ];
                }
                Db::name('cg_system_ci')->insertAll($temp);
            }

            //增加经销商信息信息表

            $temp  = [];

            //默认经销商信息并插入
            $temp[] = [
                'jxs_id'=>$data['jxs'],
                'system_id'=>$insetid,
                'brief'=>'',
                'cuser'=>$_SESSION['think']['employee_id'],
                'ctime'=>time(),
                'puser'=>$_SESSION['think']['employee_id'],
                'ptime'=>time(),
                'default'=>1,
            ];
            if(isset($jxs)&&is_array($jxs)){
                foreach($jxs['id'] as $k=>$v){
                    if($v=='')
                        continue;
                    $temp[] = [
                        'jxs_id'=>$v,
                        'system_id'=>$insetid,
                        'brief'=>$jxs['brief'][$k],
                        'cuser'=>$_SESSION['think']['employee_id'],
                        'ctime'=>time(),
                        'puser'=>$_SESSION['think']['employee_id'],
                        'ptime'=>time(),
                        'default'=>0
                    ];
                }

            }
            Db::name('cg_system_jxs')->insertAll($temp);

            //生成添加系统申请表单
            $insert = [];
            $insert['puser'] = Session::get('employee_id');
            $insert['ptime'] = time();
            $insert['system_id'] = $insetid;
            $insert['isdel'] = 0;
            $insert['aplType'] = 0; //添加系统类型
            Db::name('cg_system_approval')->insert($insert);
            echo  json_encode([
                "success"=>true,
                "msg"=>"添加成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"添加失败"
            ]);die;
        }

    }

    public function addview(){
        if($_POST){
            $data = [];
            $data['zoning'] = $this->request->post('zoning');
            $data['provice'] = $this->request->post('provice');
            $data['city'] = $this->request->post('city');
            $data['jxs'] = $this->request->post('jxs');
            $validate = new Valid([
                'zoning'  => 'require',
                'provice'  => 'require',
                'city'  => 'require',
                'jxs'  => 'require',
            ]);


            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>true,
                    "msg"=>"验证成功",
                    "id"=>"验证成功"
                ]);die;
            }


            die;
        }
        $zoning = model('Zoning')->select();
        $this->assign('zoning',$zoning);
        return $this->fetch();
    }

    public function addviewnext(){
        $get = Request::instance()->get();
        $this->assign('get',$get);

        //查询一级渠道类型
        $channel_type1 = Db::table('cg_channel_types1')->field('title,id')->select();
        $this->assign('channel_type1',$channel_type1);

        //查询客户类型
        $customer_type = Db::table('cg_customertype')->field('title,id')->select();
        $this->assign('customer_type',$customer_type);

        //查询默认经销商
        $default_jxs = Db::table('cg_jxs')->field('brief,title,id,sn,city,provice,zoning')->where(array('id'=>$get['jxs']))->find();
        $default_jxs['city'] = Db::table('cg_market_city t')->join('employee t2','t2.id= t.head')->where('t.id',$default_jxs['city'])->value('t2.em_name');
        $default_jxs['provice'] = Db::table('cg_market_provice t')->join('employee t2','t2.id= t.head')->where('t.id',$default_jxs['provice'])->value('t2.em_name');
        $default_jxs['zoning'] = Db::table('cg_market_zoning t')->join('employee t2','t2.id= t.head')->where('t.id',$default_jxs['zoning'])->value('t2.em_name');
        $this->assign('default_jxs',$default_jxs);

        return $this->fetch();
    }

    /**
     * 查询经销商的部分信息
     */
    public function findJxs(){
        $id = $this->request->post('id');
        $data = Db::table('cg_jxs')->where('id',$id)->field('sn,zoning,provice,city')->find();
        $data['city'] = Db::table('cg_market_city t')->join('employee t2','t2.id= t.head')->where('t.id',$data['city'])->value('t2.em_name');
        $data['provice'] = Db::table('cg_market_provice t')->join('employee t2','t2.id= t.head')->where('t.id',$data['provice'])->value('t2.em_name');
        $data['zoning'] = Db::table('cg_market_zoning t')->join('employee t2','t2.id= t.head')->where('t.id',$data['zoning'])->value('t2.em_name');
        echo json_encode($data);die;
    }

    public function twoCType(){
        $id = $this->request->get('id');
        //查询二级渠道类型
        $channel_type2 = Db::table('cg_channel_types2')->where('pid',$id)->field('title,id')->select();
        echo '<option value="">请选择</option>';
        foreach($channel_type2 as $k=>$v) {
            echo '<option value="'.$v['id'].'">'.$v['title'].'</option>';
        }
    }

    public function selectJXS(){
        return $this->fetch();
    }

    //返回分区经销商树数据
    public function zonetreeajax(){
        $data = Db::table('cg_market_zoning')->where('isdel',0)->field('id,title')->select();//查分区
        $data2 = [];
        foreach($data as $k=>$v){
            $temp = [];
            $temp['name'] = $v['title'];
            //查询省份
            $t = Db::table('cg_market_provice')->where(array('zoning'=>$v['id']))->field('id,title')->select();//查省份
            $data3 = [];
            foreach($t as $kk=>$vv){
                $temp2['name'] = $vv['title'];
                //查城市
                $tt = Db::table('cg_market_city')->where(array('provice'=>$vv['id']))->field('id,title')->select();//查城市
                $data4 = [];
                foreach($tt as $k3=>$v3){
                    $temp3['name'] = $v3['title'];
                    //查城市
                    $t3 = Db::table('cg_jxs')->where(array('city'=>$v3['id']))->field('id,title name')->select();//查经销商
                    $temp3['children'] = $t3;
                    $temp3["chkDisabled"]=true;
                    $temp3["nocheck"]=true;
                    $data4[] = $temp3;
                }
                $temp2['children'] = $data4;
                $temp2["chkDisabled"]=true;
                $temp2["nocheck"]=true;
                $data3[] = $temp2;
            }
            $temp['children'] = $data3;
            $temp["chkDisabled"]=true;
            $temp["nocheck"]=true;
            $data2[] = $temp;
        }
        echo json_encode($data2);
    }

    public function updateview(){
        $id = $this->request->param('id');

        if($_POST){
            $attach = $this->request->post('attach');
            if($attach){
                $attachids = $attach;
                $attach = serialize(explode(',',$attach));

                //记录日志-备份原记录
                $old = $this->log_start($id);
                $bool = Db::table('cg_system')->where('id',$id)->update(['attach'=>$attach]);
                //记录日志-开始记录
                $this->log_end($id,$old);

                if(isset($attachids)){
                    Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$id,'target_table'=>'cg_system'));
                }
                if(false!==$bool){
                    echo json_encode(['success'=>true,'msg'=>'附件提交成功']);
                }else{
                    echo json_encode(['success'=>false,'msg'=>'附件提交失败']);
                }
            }
            die;
        }

        $data = Db::table('cg_system')->where('id',$id)->find();

        if($data['stuff']){
            $data['stuff'] = unserialize($data['stuff']);
            foreach($data['stuff'] as $k=>$v){
                $data['stuff'][$k] = ['em_name'=>Db::table('employee')->where('id',$v)->value('em_name'),'id'=>$v];
            }
        }

        //查询系统所属经销商
        $jxs = Db::table('cg_system_jxs')->where('system_id',$id)->order('`default` desc')->select();
        foreach($jxs as $k=>$v){
            $jxs[$k]['title'] = Db::table('cg_jxs')->field('title')->where('id',$v['jxs_id'])->value('title');
            $jxs[$k]['sn'] = Db::table('cg_jxs')->field('sn')->where('id',$v['jxs_id'])->value('sn');
            $jxs[$k]['zoning_head'] = Db::table('cg_jxs t')->join('cg_market_zoning t2','t2.id=t.zoning')->join('employee t3','t2.head=t3.id')->field('t3.em_name')->where('t.id',$v['jxs_id'])->value('t3.em_name');
            $jxs[$k]['provice_head'] = Db::table('cg_jxs t')->join('cg_market_provice t2','t2.id=t.provice')->join('employee t3','t2.head=t3.id')->field('t3.em_name')->where('t.id',$v['jxs_id'])->value('t3.em_name');
            $jxs[$k]['city_head'] = Db::table('cg_jxs t')->join('cg_market_city t2','t2.id=t.city')->join('employee t3','t2.head=t3.id')->field('t3.em_name')->where('t.id',$v['jxs_id'])->value('t3.em_name');
        }
        $data['jxss'] = $jxs;
        $data['ci'] = Db::table('cg_system_ci')->where('system_id',$id)->select();
        if($data['attach']){
            $attach = unserialize($data['attach']);
            foreach($attach as $k=>$v){
                $filename = Db::table('annex')->where('id',$v)->value('file_name');
                $path =  Db::table('annex')->where('id',$v)->value('path');
                $attach[$k] = ['link'=>'/uploads'.DS.$path,'file_name'=>$filename,'id'=>$v];
            }
            $data['attach'] = $attach;
        }

        //查询系统评价信息
        $evaluation = Db::table('cg_system_evaluation')->where(['system_id'=>$id,'cuser'=>Session::get('employee_id')])->find();
        $data['evaluation'] = $evaluation;
        $this->assign('data',$data);

        //查询一级渠道类型
        $channel_type1 = Db::table('cg_channel_types1')->field('title,id')->select();
        $this->assign('channel_type1',$channel_type1);
        //查询一级渠道类型
        $channel_type2 = Db::table('cg_channel_types2')->field('title,id')->where('pid',$data['oneCType'])->select();
        $this->assign('channel_type2',$channel_type2);

        //查询客户类型
        $customer_type = Db::table('cg_customertype')->field('title,id')->select();
        $this->assign('customer_type',$customer_type);

        //查询默认经销商
        $default_jxs = Db::table('cg_jxs')->field('brief,title,id,sn,city,provice,zoning')->where(array('id'=>$data['jxs']))->find();

        $default_jxs['city'] = Db::table('cg_market_city t')->join('employee t2','t2.id= t.head')->where('t.id',$default_jxs['city'])->value('t2.em_name');
        $default_jxs['provice'] = Db::table('cg_market_provice t')->join('employee t2','t2.id= t.head')->where('t.id',$default_jxs['provice'])->value('t2.em_name');
        $default_jxs['zoning'] = Db::table('cg_market_zoning t')->join('employee t2','t2.id= t.head')->where('t.id',$default_jxs['zoning'])->value('t2.em_name');
        $this->assign('default_jxs',$default_jxs);


        //查询系统管理日志
        $log = Db::table('cg_system_log')->where('system_id',$id)->order('ctime desc')->select();
        foreach($log as $k=>$v){
            $log[$k]['cuser'] = Db::table('users')->where('id',$v['cuser'])->value('login_name');
        }
        $this->assign('system_log',$log);

        return $this->fetch();
    }

    //查询部门负责人
    public function selecthead(){
        return $this->fetch();
    }

    //查询部门负责人
    public function selectadmin(){
        return $this->fetch();
    }

    //递归查询所有部门和人员。
    public function searchAllDE($id){
        //查询部门和人员
        $data = Db::query("select id,de_name from department where parent_id={$id}");
        if($data){

            //查询子部门
            foreach($data as $k=>$v){
                $child = $this->searchAllDE($v['id']);
                if($child)
                    $data[$k]['_child'] = $child;
                //查询该部门直接下属的人员
                $employees = Db::query("select t.id,t.em_name from employee t join department_employee t2 on t2.employee_id=t.id where t2.index=1 and t2.department_id=".$v['id']);
                if($employees)
                    $data[$k]['employees'] = $employees;
            }
            return $data;
        }else{
            return;
        }
    }

    //查询所有经销商
    public function provicejson(){
        //查询所有省份
        $data = Db::table('employee')->field('em_name,id')->select();

        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }

    //查询所有经销商
    public function jxsjson(){
        //查询所有省份
        $data = Db::table('cg_jxs')->field('title em_name,id')->select();

        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }

    public function update(){

        $id = $this->request->param('id');
        $validate = new Valid([
            'id' => 'require|number',
            'title'  => 'require|max:100|unique:cg_system|checkJxsmc',
            'stuff'  => 'require',
            'cusType'  => 'require',
            'oneCType'  => 'require',
            'twoCType'  => 'require',
            'detailAddress'  => 'require',
        ]);

        $data = [];
        $data['title'] = $this->request->post('title');
        $data['id'] = $this->request->param('id');
        $data['cusType'] = $this->request->post('cusType');
        $data['oneCType'] = $this->request->post('oneCType');
        $data['twoCType'] = $this->request->post('twoCType');
        $data['detailAddress'] = $this->request->post('detailAddress');
        $data['brief'] = $this->request->post('brief');
        $data['stuff'] = $this->request->post('stuff');
        $data['attach'] = $this->request->post('attach');
        if (!$validate->check($data)) {
            echo  json_encode([
                "success"=>false,
                "msg"=>$validate->getError()
            ]);die;
        }

        $data['stuff'] = explode(',',$data['stuff']);
        $data['stuff'] = serialize($data['stuff']);
        $data['cuser'] = $_SESSION['think']['employee_id'];
        $data['ctime'] = time();
        $data['puser'] = $_SESSION['think']['employee_id'];
        $data['ptime'] = time();

        //先把旧的附件查出来
        $aids = Db::table('cg_system')->where('id',$id)->value('attach');
        if($aids){
            $aids = unserialize($aids);
        }
        if(!is_array($aids)){
            $aids = [];
        }

        //删除附件
        $remove = $this->request->post('remove');
        if($remove){
            $aids = array_diff($aids,explode(',',$remove));
        }


        if($data['attach']){ //有新附件,合并新旧附件(如果有要删除的附件那么旧附件是去除这些要删除的附件的旧附件)

            $attachids = $data['attach'];
            $data['attach'] = serialize(array_merge(explode(',',$data['attach']),$aids));

        }elseif($remove){ //没有新附件但是有要删除的附件

            $data['attach'] = serialize($aids);

        }else{ //没有新附件也没有要删除的附件,无需修改附件字段

            unset($data['attach']);

        }

        $jxsll = $this->request->post('systemContact/a');
        $jxs = $this->request->post('jxs/a');

        //记录日志-备份原记录
        $old = $this->log_start($id);
        $bool = Db::table('cg_system')->where(array('id'=>$id))->update($data);
//        echo Db::table('cg_system')->getLastSql();
        if(false !== $bool){

            //记录日志-开始记录
            $this->log_end($id,$old);

            //更新附件表
            if(isset($attachids)){
                Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$id,'target_table'=>'cg_system'));
            }

            //附件标注为删除
            if($remove){
                Db::table('annex')->where('id','in',$remove)->update(['isdel'=>1]);
            }

            //增加附属系统联络信息表
            if(isset($jxsll)&&is_array($jxsll)){
                $temp  = [];

                foreach($jxsll['name'] as $k=>$v){
                    if($v=='')
                        continue;
                    $temp[] = [
                        'name'=>$v,
                        'system_id'=>$id,
                        'phone'=>$jxsll['phone1'][$k].'-'.$jxsll['phone2'][$k],
                        'mobile'=>$jxsll['mobile'][$k],
                        'fax'=>$jxsll['fax1'][$k].'-'.$jxsll['fax2'][$k],
                        'email'=>$jxsll['email'][$k],
                        'job'=>$jxsll['job'][$k],
                        'addr'=>$jxsll['addr'][$k],
                        'zipcode'=>$jxsll['zipcode'][$k],
                        'cuser'=>$_SESSION['think']['employee_id'],
                        'ctime'=>time(),
                        'puser'=>$_SESSION['think']['employee_id'],
                        'ptime'=>time(),
                    ];
                }
                Db::name('cg_system_ci')->insertAll($temp);
            }

            //增加系统经销商信息表
            if(isset($jxs)&&is_array($jxs)){
                $temp  = [];

                foreach($jxs['id'] as $k=>$v){
                    if($v=='')
                        continue;

                    //查询经销商信息是否

                    //判断经销商信息是否已经存在
                    $where = [
                        'system_id'=>$id,
                        'jxs_id'=>$v,
                    ];
                    $count = Db::table('cg_system_jxs')->where($where)->count();
//                    echo Db::table('cg_system_jxs')->getLastSql();die;
                    if($count>0){
                        //判断brief字段是否有修改
                        $count = Db::table('cg_system_jxs')->where($where)->value('brief');
                        if($count != $jxs['brief'][$k]){
                            //只修改brief字段
                            Db::table('cg_system_jxs')->where($where)->update(['brief'=>$jxs['brief'][$k]]);
                        }
                        continue;
                    }

                    $temp[] = [
                        'jxs_id'=>$v,
                        'system_id'=>$id,
                        'brief'=>$jxs['brief'][$k],
                        'cuser'=>$_SESSION['think']['employee_id'],
                        'ctime'=>time(),
                        'puser'=>$_SESSION['think']['employee_id'],
                        'ptime'=>time(),
                        'default'=>0
                    ];
                }


                Db::name('cg_system_jxs')->insertAll($temp);
            }
            echo  json_encode([
                "success"=>true,
                "msg"=>"修改成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"修改失败"
            ]);die;
        }

    }

    public function delete(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $data = [];
        $data['isdel'] = 1;
        //记录日志-备份原记录
        $old = $this->log_start($id);
        $bool = Db::table('cg_system')->where(array('id'=>$id))->update($data);
        if(false !== $bool){
            //记录日志-开始记录
            $this->log_end($id,$old);
            echo  json_encode([
                "success"=>true,
                "msg"=>"删除成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"删除失败"
            ]);die;
        }
    }

    //批量删除系统及下属网点
    public function batchDel(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $data = [];
        $data['isdel'] = 1;
        //记录日志-备份原记录
        $old = $this->log_start($id);
        $bool = Db::table('cg_system')->where(array('id'=>$id))->update($data);

        if(false !== $bool){
            //删除网点
            Db::table('cg_net')->where(array('system_id'=>$id))->update($data);
            //记录日志-开始记录
            $this->log_end($id,$old);
            echo  json_encode([
                "success"=>true,
                "msg"=>"删除成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"删除失败"
            ]);die;
        }
    }

    public function qiyong(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $data = [];
        $data['isdel'] = 0;
        //记录日志-备份原记录
        $old = $this->log_start($id);
        $bool = Db::table('cg_system')->where(array('id'=>$id))->update($data);
        if(false !== $bool){
            //记录日志-开始记录
            $this->log_end($id,$old);
            echo  json_encode([
                "success"=>true,
                "msg"=>"启用成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"启用失败"
            ]);die;
        }
    }

    public function isdel()
    {
        $title = $this->request->get('title');
        $sn = $this->request->get('sn');
        $zoning = $this->request->get('zoning');
        $provice = $this->request->get('provice');
        $city = $this->request->get('city');
        $zoning_head = $this->request->get('zoning_head');
        $provice_head = $this->request->get('provice_head');
        $stuff = $this->request->get('stuff');
        $wdXianShiLeiXing = $this->request->get('wdXianShiLeiXing');
        $this->assign(array('title'=>$title));
        $this->assign(array('sn'=>$sn));
        $this->assign(array('zoning'=>$zoning));
        $this->assign(array('provice'=>$provice));
        $this->assign(array('city'=>$city));
        $this->assign(array('zoning_head'=>$zoning_head));
        $this->assign(array('provice_head'=>$provice_head));
        $this->assign(array('stuff'=>$stuff));
        $where = [];
        $where['t.isdel'] = 1;
        $where['t2.isdel'] = 0;
        if($wdXianShiLeiXing==0)
            $where['t2.default'] = 1;//只查默认经销商
        if($title)
            $where['title'] = array('like','%'.$title.'%');
        if($sn)
            $where['title'] = array('like','%'.$sn.'%');
        if($zoning&&!$zoning_head)
            $where['zoning'] = array('exp','in(select id from cg_market_zoning where title like "%'.$zoning.'%")');
        if($provice&&!$provice_head)
            $where['provice'] = array('exp','in(select id from cg_market_provice where title like "%'.$provice.'%")');
        if($city)
            $where['city'] = array('exp','in(select id from cg_market_city where title like "%'.$city.'%")');
        if($zoning_head&&!$zoning)
            $where['zoning'] = array('exp','in(select t.id from cg_market_zoning t join employee t2 on t2.id=t.head where t2.em_name like "%'.$zoning_head.'%")');
        if($provice_head&&!$provice)
            $where['provice'] = array('exp','in(select t.id from cg_market_provice t join employee t2 on t2.id=t.head where t2.em_name like "%'.$provice_head.'%")');
        if($provice_head&&$provice)
            $where['provice'] = array('exp','in(select t.id from cg_market_provice t join employee t2 on t2.id=t.head where t2.em_name like "%'.$provice_head.'%") and provice in(select id from cg_market_provice where title like "%'.$provice.'%") ');
        if($zoning_head&&$zoning)
            $where['zoning'] = array('exp','in(select t.id from cg_market_zoning t join employee t2 on t2.id=t.head where t2.em_name like "%'.$zoning_head.'%") and zoning in(select id from cg_market_zoning where title like "%'.$zoning.'%") ');
        if($stuff){
            //根据模糊查询规则把admin对应的id全部查询出来
            $ids = Db::query("select id from employee where em_name like '%{$stuff}%'");
            $str = [];
            foreach($ids as $k=>$v){
                if($k==0)
                    $str[] = " like '%\"$v[id]\"%' ";
                else
                    $str[] = " stuff like '%\"$v[id]\"%' ";
            }
            $str = implode('or',$str);

            $where['stuff'] = array('exp',$str);
        }

        $count = Db::table('cg_system t')->join('cg_system_jxs t2','t2.system_id=t.id')->where($where)->count();
        $data = Db::table('cg_system t')->field('*,t.id id')->join('cg_system_jxs t2','t2.system_id=t.id')->order("t.id desc")->where($where)->paginate(10,$count);
//        echo Db::table('cg_system')->getLastSql();
        $page = $data->render();
        $data = $data->items();
        foreach($data as $k=>$v){
            $data[$k]['cusername'] = Db::table('users')->where(array('id'=>$v['cuser']))->value('login_name');
            $data[$k]['pusername'] = Db::table('users')->where(array('id'=>$v['puser']))->value('login_name');
            $temp = unserialize($v['stuff']);
            $temp = implode(',',$temp);
            $temp = Db::query("select em_name from employee where id in(".$temp.")");
            $temp2 = [];
            foreach($temp as $v1){
                $temp2[] = $v1['em_name'];
            }
            $data[$k]['stuff'] = $temp2;
            $data[$k]['jxs_title'] = Db::table('cg_jxs')->where(array('id'=>$v['jxs_id']))->value('title');
            $data[$k]['jxs_stuff'] = Db::table('cg_jxs')->where(array('id'=>$v['jxs_id']))->value('stuff');
            $temp = unserialize($data[$k]['jxs_stuff']);
            $temp = implode(',',$temp);
            $temp = Db::query("select em_name from employee where id in(".$temp.")");
            $temp2 = [];
            foreach($temp as $v1){
                $temp2[] = $v1['em_name'];
            }
            $data[$k]['jxs_stuff']= $temp2;
            $data[$k]['cusType'] = Db::table('cg_customertype')->where(array('id'=>$v['cusType']))->value('title');
            $data[$k]['oneCType'] = Db::table('cg_channel_types1')->where(array('id'=>$v['oneCType']))->value('title');
            $data[$k]['twoCType'] = Db::table('cg_channel_types2')->where(array('id'=>$v['twoCType']))->value('title');
            $data[$k]['zoning_title'] = Db::table('cg_market_zoning')->where(array('id'=>$v['zoning']))->value('title');
            $data[$k]['provice_title'] = Db::table('cg_market_provice')->where(array('id'=>$v['provice']))->value('title');
            $data[$k]['city_title'] = Db::table('cg_market_city')->where(array('id'=>$v['city']))->value('title');
            $data[$k]['zoning_head'] = Db::table('cg_market_zoning t')->join('employee t2','t.head=t2.id')->where(array('t.id'=>$v['zoning']))->value('t2.em_name');
            $data[$k]['provice_head'] = Db::table('cg_market_provice t')->join('employee t2','t.head=t2.id')->where(array('t.id'=>$v['provice']))->value('t2.em_name');
            $data[$k]['city_head'] = Db::table('cg_market_city t')->join('employee t2','t.head=t2.id')->where(array('t.id'=>$v['city']))->value('t2.em_name');
            $data[$k]['ctime'] = date('Y-m-d H:i',$v['ctime']);
            $data[$k]['ptime'] = date('Y-m-d H:i',$v['ptime']);
        }

        $this->assign('data',$data);
        $this->assign('page',$page);
        return $this->fetch('');
    }

    public function lendSystem(){
        return $this->fetch();
    }

    public function plamendSystem(){
        return $this->fetch();
    }

    /**
     * 查看系统明细
     * @return mixed
     */
    public function view(){

        $id = $this->request->param('id');

        if($_POST){
            $attach = $this->request->post('attach');

            //先把旧的附件查出来
            $aids = Db::table('cg_system')->where('id',$id)->value('attach');
            $old = $aids;
            if($aids){
                $aids = unserialize($aids);
            }
            if(!is_array($aids)){
                $aids = [];
            }

            //删除附件
            $remove = $this->request->post('remove');
            if($remove){

                $aids = array_diff($aids,explode(',',$remove));
                Db::table('annex')->where('id','in',$remove)->update(['isdel'=>1]);
//                echo Db::table('annex')->getLastSql();
            }

            //新增附件
            if($attach) {
                $attachids = $attach;
                //新旧合并
                $attach = serialize(array_merge(explode(',', $attach), $aids));
            }else { //非新增
                $attach = serialize($aids);
            }

            //记录日志-备份原记录
            $old = $this->log_start($id);
            Db::table('cg_system')->where('id',$id)->update(['attach'=>$attach]);
            if(isset($attachids)){
                //记录日志-开始记录
                $this->log_end($id,$old);
                Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$id,'target_table'=>'cg_system'));
            }


            if($remove||$attach){
                echo json_encode(['success'=>true,'msg'=>'附件提交成功']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'附件提交失败']);
            }

            die;
        }

        $data = Db::table('cg_system')->where('id',$id)->find();
        if($data['stuff']){
            $data['stuff'] = unserialize($data['stuff']);
            foreach($data['stuff'] as $k=>$v){
                $data['stuff'][$k] = Db::table('employee')->where('id',$v)->value('em_name');
            }
            $data['stuff'] = implode(',',$data['stuff']);
        }
        $data['cusType'] = Db::table('cg_customertype')->where('id',$data['cusType'])->value('title');
        $data['oneCType'] = Db::table('cg_channel_types1')->where('id',$data['oneCType'])->value('title');
        $data['twoCType'] = Db::table('cg_channel_types2')->where('id',$data['twoCType'])->value('title');
        //查询系统所属经销商
        $jxs = Db::table('cg_system_jxs')->where('system_id',$id)->order('`default` desc')->select();
        foreach($jxs as $k=>$v){
            $jxs[$k]['title'] = Db::table('cg_jxs')->field('title')->where('id',$v['jxs_id'])->value('title');
            $jxs[$k]['sn'] = Db::table('cg_jxs')->field('sn')->where('id',$v['jxs_id'])->value('sn');
            $jxs[$k]['zoning_head'] = Db::table('cg_jxs t')->join('cg_market_zoning t2','t2.id=t.zoning')->join('employee t3','t2.head=t3.id')->field('t3.em_name')->where('t.id',$v['jxs_id'])->value('t3.em_name');
            $jxs[$k]['provice_head'] = Db::table('cg_jxs t')->join('cg_market_provice t2','t2.id=t.provice')->join('employee t3','t2.head=t3.id')->field('t3.em_name')->where('t.id',$v['jxs_id'])->value('t3.em_name');
            $jxs[$k]['city_head'] = Db::table('cg_jxs t')->join('cg_market_city t2','t2.id=t.city')->join('employee t3','t2.head=t3.id')->field('t3.em_name')->where('t.id',$v['jxs_id'])->value('t3.em_name');
        }
        $data['jxs'] = $jxs;
        $data['ci'] = Db::table('cg_system_ci')->where('system_id',$id)->select();
        if($data['attach']){
            $attach = unserialize($data['attach']);
            foreach($attach as $k=>$v){
                $filename = Db::table('annex')->where('id',$v)->value('file_name');
                $path =  Db::table('annex')->where('id',$v)->value('path');
                $attach[$k] = ['link'=>DS.'uploads'.DS.$path,'file_name'=>$filename,'id'=>$v];
            }
            $data['attach'] = $attach;
        }

        //查询系统评价信息
        $evaluation = Db::table('cg_system_evaluation')->where(['system_id'=>$id,'cuser'=>Session::get('employee_id')])->find();
        $data['evaluation'] = $evaluation;

        //查询旗下网点数
        $data['net_num'] = Db::table('cg_net')->where('system_id',$id)->count();
        $data['nets'] = Db::table('cg_net')->where('system_id',$id)->field('id,title')->select();

        $this->assign('data',$data);
        return $this->fetch();
    }

    public function getjxses(){
        $id = $this->request->get('id');
        $fenqu = Db::table('cg_jxs')->where(array('city'=>$id))->field('id,title')->select();
        echo '<option value="">请选择</option>';
        foreach($fenqu as $k=>$v) {
            echo '<option value="'.$v['id'].'">'.$v['title'].'</option>';
        }
    }

    /**
     * 提交评价
     */
    public function subEvaluation(){
        $data = [];
        $data['cooIntention'] = $this->request->post('cooIntention');
        $data['cusSize'] = $this->request->post('cusSize');
        $data['cusInfluence'] = $this->request->post('cusInfluence');
        $data['cusCovArea'] = $this->request->post('cusCovArea');
        $data['system_id'] = $this->request->post('system_id');
        $data['cuser'] = Session::get('employee_id');
        $data['ctime'] = time();

        $evaluation = Db::table('cg_system_evaluation')->where(['system_id'=>$data['system_id'],'cuser'=>Session::get('employee_id')])->count();
        if($evaluation>0){
            echo  json_encode([
                "success"=>false,
                "msg"=>"不能重复评价"
            ]);die;
        }
        $bool = Db::table('cg_system_evaluation')->insert($data);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"评价成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"评价失败"
            ]);die;
        }
    }

    /**
     * 删除联系人
     */
    public function delContact(){
        $id = $this->request->post('id');
        $bool = Db::table('cg_system_ci')->where('id',$id)->update(['isdel'=>1]);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"删除成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"删除失败"
            ]);die;
        }
    }

    /**
     * 启用联系人
     */
    public function enaContact(){
        $id = $this->request->post('id');
        $bool = Db::table('cg_system_ci')->where('id',$id)->update(['isdel'=>0]);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"启用成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"启用失败"
            ]);die;
        }
    }

    /**
     * 替换经销商
     * @return mixed
     * @throws \think\Exception
     */
    public function repDealer(){
        if($_POST){
            $data = [];
            $data['zoning'] = $this->request->post('zoning');
            $data['provice'] = $this->request->post('provice');
            $data['city'] = $this->request->post('city');
            $data['jxs'] = $this->request->post('jxs');
            $id = $this->request->param('id');

            $validate = new Valid([
                'zoning'  => 'require',
                'provice'  => 'require',
                'city'  => 'require',
                'jxs'  => 'require',
            ]);


            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }

            $old_jxs = Db::table('cg_system')->where('id',$id)->value('jxs');
            //记录日志-备份原记录
            $old = $this->log_start($id);
            $bool = Db::table('cg_system')->where('id',$id)->update($data);
            if(false !== $bool){
                //记录日志-开始记录
                $this->log_end($id,$old);
                $cnt = Db::table('cg_system_jxs')
                    ->where([
                        'system_id'=>$id,
                        'jxs_id'=>$old_jxs,
                        'default'=>1
                    ])->count();
                if($cnt>0){
                    Db::table('cg_system_jxs')
                        ->where([
                            'system_id'=>$id,
                            'jxs_id'=>$old_jxs,
                            'default'=>1
                        ])
                        ->update([
                            'jxs_id'=>$data['jxs']
                        ]);
                }else{
                    Db::table('cg_system_jxs')
                        ->insert([
                            'jxs_id'=>$data['jxs'],
                            'system_id'=>$id,
                            'default'=>1,
                            'cuser'=>session('employee_id'),
                            'puser'=>session('employee_id'),
                            'ctime'=>time(),
                            'ptime'=>time(),
                        ]);
                }

                echo  json_encode([
                    "success"=>true,
                    "msg"=>"替换成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"替换失败"
                ]);die;
            }
        }
        $zoning = model('Zoning')->select();
        $this->assign('zoning',$zoning);
        return $this->fetch();
    }

    //系统操作日志
    public function log_start($id){
        $data = Db::table('cg_system')->where('id',$id)->find();
        return $data;
    }
    //系统操作日志
    public function log_end($id,$old){
        $new = Db::table('cg_system')->where('id',$id)->find();
        $msg = [];
        if($new&&$old){
            if($old['title'] != $new['title']){
                $msg[] = '系统名称由‘'.$old['title'].'’变成‘'.$new['title'].'’';
            }
            if(trim($old['brief']) != trim($new['brief'])){
                $msg[] = '描述信息由‘'.$old['brief'].'’变成‘'.$new['brief'].'’';
            }
            if($old['zoning'] != $new['zoning']){
                $msg[] = '所属大区由‘'.Db::table('cg_market_zoning')->where('id',$old['zoning'])->value('title').'’变成‘'.Db::table('cg_market_zoning')->where('id',$new['zoning'])->value('title').'’';
            }
            if($old['provice'] != $new['provice']){
                $msg[] = '所属省份由‘'.Db::table('cg_market_provice')->where('id',$old['provice'])->value('title').'’变成‘'.Db::table('cg_market_provice')->where('id',$new['provice'])->value('title').'’';
            }
            if($old['city'] != $new['city']){
                $msg[] = '所属城市由‘'.Db::table('cg_market_city')->where('id',$old['city'])->value('title').'’变成‘'.Db::table('cg_market_city')->where('id',$new['city'])->value('title').'’';
            }
            if($old['sn'] != $new['sn']){
                $msg[] = '系统编号由‘'.$old['sn'].'’变成‘'.$new['sn'].'’';
            }
            if($old['oneCType'] != $new['oneCType']){
                $msg[] = '所属一级渠道类型由‘'.Db::table('cg_channel_types1')->where('id',$old['oneCType'])->value('title').'’变成‘'.Db::table('cg_channel_types1')->where('id',$new['oneCType'])->value('title').'’';
            }
            if($old['twoCType'] != $new['twoCType']){
                $msg[] = '所属二级渠道类型由‘'.Db::table('cg_channel_types2')->where('id',$old['twoCType'])->value('title').'’变成‘'.Db::table('cg_channel_types2')->where('id',$new['twoCType'])->value('title').'’';
            }
            if($old['jxs'] != $new['jxs']){
                $msg[] = '默认经销商由‘'.Db::table('cg_jxs')->where('id',$old['jxs'])->value('title').'’变成‘'.Db::table('cg_jxs')->where('id',$new['jxs'])->value('title').'’';
            }
            if($old['cusType'] != $new['cusType']){
                $msg[] = '客户类型由‘'.Db::table('cg_customertype')->where('id',$old['cusType'])->value('title').'’变成‘'.Db::table('cg_customertype')->where('id',$new['cusType'])->value('title').'’';
            }
            if($old['detailAddress'] != $new['detailAddress']){
                $msg[] = '详细地址由‘'.$old['detailAddress'].'’变成‘'.$new['detailAddress'].'’';
            }

            if($old['stuff'] != $new['stuff']){
                if($old['stuff']&&$new['stuff']){
                    $old['stuff'] = unserialize($old['stuff']);
                    $new['stuff'] = unserialize($new['stuff']);
                    $add = array_diff($new['stuff'],$old['stuff']);
                    $del = array_diff($old['stuff'],$new['stuff']);
                    if($add){
                        $add = implode(',',$add);
                        $daibiao = Db::table('employee')->where("id in($add)")->field('em_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['em_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '添加了业务代表'.$daibiao2;
                    }
                    if($del){
                        $del = implode(',',$del);
                        $daibiao = Db::table('employee')->where("id in($del)")->field('em_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['em_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '删除了业务代表'.$daibiao2;
                    }
                }elseif($old['stuff']){
                    $old['stuff'] = unserialize($old['stuff']);

                    if($old['stuff']){
                        $del = implode(',',$old['stuff']);
                        $daibiao = Db::table('employee')->where("id in(".$old['stuff'].")")->field('em_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['em_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '删除了业务代表'.$daibiao2;
                    }
                }else{
                    $new['stuff'] = unserialize($new['stuff']);
                    $add = $new['stuff'];
                    if($add){
                        $add = implode(',',$add);
                        $daibiao = Db::table('employee')->where("id in($add)")->field('em_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['em_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '添加了业务代表'.$daibiao2;
                    }
                }
            }

            if($old['attach'] != $new['attach']){
                if($old['attach']&&$new['attach']){
                    $old['attach'] = unserialize($old['attach']);
                    $new['attach'] = unserialize($new['attach']);
                    $add = array_diff($new['attach'],$old['attach']);
                    $del = array_diff($old['attach'],$new['attach']);
                    if($add){
                        $add = implode(',',$add);
                        $daibiao = Db::table('annex')->where("id in($add)")->field('file_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['file_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '添加了附件'.$daibiao2;
                    }
                    if($del){
                        $del = implode(',',$del);
                        $daibiao = Db::table('annex')->where("id in($del)")->field('file_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['file_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '删除了附件'.$daibiao2;
                    }
                }elseif($old['attach']){
                    $old['attach'] = unserialize($old['attach']);

                    if($old['attach']){
                        $del = implode(',',$old['attach']);
                        $daibiao = Db::table('annex')->where("id in(".$old['attach'].")")->field('file_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['file_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '删除了附件'.$daibiao2;
                    }
                }else{
                    $new['attach'] = unserialize($new['attach']);
                    $add = $new['attach'];
                    if($add){
                        $add = implode(',',$add);
                        $daibiao = Db::table('annex')->where("id in($add)")->field('file_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['file_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '添加了附件'.$daibiao2;
                    }
                }
            }

            if($old['isdel'] != $new['isdel']){
                if($old['isdel'] ==1)
                    $msg[] = '从回收站重新启用了该经销商';
                else
                    $msg[] = '把该经销商挪到了回收站';
            }


            if($old['groupid'] != $new['groupid']){
                $msg[] = '系统分组由‘'.Db::table('cg_system_group')->where('id',$old['groupid'])->value('title').'’变成‘'.Db::table('cg_system_group')->where('id',$new['groupid'])->value('title').'’';
            }

            if($old['isApp'] != $new['isApp']){
                if($old['isApp'] ==0)
                    $msg[] = '系统由待审状态变为审核通过';
                else
                    $msg[] = '系统由审核通过变为待审状态';
            }

            if($msg){
                $msg = '修改了编号为\''.$old['sn'].'\'的系统‘'.$old['title'].'’,'.implode(',',$msg);
                //插入日志
                Db::table('cg_system_log')->insert(['content'=>$msg,
                    'system_id'=>$new['id'],
                    'cuser'=>Session::get("employee_id"),
                    'ctime'=>time()
                ]);
            }

        }
    }

    //标注地图
    public function map(){
        $id = $this->request->param('id');
        if($_POST){
            $data = [];
            $data['lng'] = $this->request->post('lng');
            $data['lat'] = $this->request->post('lat');
            $data['detailAddress'] = $this->request->post('detailAddress');

            $bool = Db::table('cg_system')->where('id',$id)->update($data);
            if(false !== $bool){
                echo json_encode(['success'=>true,'msg'=>'ok']);die;
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);die;
            }
        }
        return $this->fetch();
    }

    //在地图上显示
    public function mapShow(){
        $id = $this->request->param('import');
        $where = [];
        if($id){
            $where['iskey'] = 1;
        }
        $data = db('cg_system')->where($where)->field('lat,lng,detailAddress,title,id')->select();
        $this->assign('data',$data);
        return $this->fetch();
    }
public function lianyingsystem(){
        return  $this->fetch();
    }
public function lianyingsystemisdel(){
        return  $this->fetch();
    }

}
